﻿using Core.Framework;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;

namespace iTool.Connector
{
    public class Program
    {
#if DEBUG
        static readonly string _iToolConnectorProcessPath = @"D:\iTool-Cloud-Framework\client.process";
#elif CLOUD
        static readonly string _iToolConnectorProcessPath = @"D:\iTool-Cloud-Framework\client.process";
#else
        static readonly string _iToolConnectorProcessPath = "/var/iTool/client.process";
#endif

        private static readonly ManualResetEvent manual = new ManualResetEvent(false);
        private static readonly MainProvider provider = new MainProvider(manual);
        private static readonly FileChangeDetect fileChangeDetect = new FileChangeDetect(_iToolConnectorProcessPath);

        static void Main(string[] args)
        {
            try
            {
                // 1. 初始化配置文件
                if (!AppSetting.ReSetiToolConfigure())
                {
                    CLog.WriteLineError("\niTool> Please input configinfomation... \n");
                    return;
                }

                // 2. 第一次启动服务
                _ = provider.StartAsync();

                // 3. 注册配置Change事件
                iToolConfigFileChangeDetect
                    .StartAndRegisterChangeEvent(async () => await provider.ReStartAsync(), iToolType.Connector);

                // 4. 注册程序注销事件
                Console.CancelKeyPress += async (sender, e) => await provider.StopAsync();
                AppDomain.CurrentDomain.ProcessExit += async (sender, e) => await provider.StopAsync();

                // 5. 注册停止
                fileChangeDetect.StartWaitResult(async value =>
                {
                    if (value == "BeginStoped")
                    {
                        await provider.StopAsync();
                        manual.Set();
                    }
                });

                // 6. Reg Waiting
                manual.WaitOne();
            }
            catch (Exception ex)
            {
#if DEBUG
                CLog.WriteLineError(ex.Message);
#else
                var logger = ProviderOfServices.GetService<ILogger<Program>>();
                logger.LogDebug(ex, "iTool.Client 退出");
#endif
            }
        }

    }

}
